const router = require('koa-router')()
const { SuccessModel, ErrorModel } = require("../model/resModel");
const {
  getList,
  getDetail,
  deleteBlog,
  updateBlog,
  newBlog,
} = require("../controller/blog");
const loginCheck = require("../middleware/loginCheck");
router.prefix('/api/blog')

router.get('/allList', async (ctx, next) => {
  const data = await getList()
  if (data) {
    ctx.body = new SuccessModel(data);
  } else {
    ctx.body = new ErrorModel(data)
  }
})
router.get('/userBloglist', loginCheck, (ctx, next) => {
  let author = ctx.session.userName;
  const keyword = ctx.query.keyword;

  if (ctx.session.isAdmin === 1) {
    // 管理员查询所有博客
    author = ''
  }

  getList(author, keyword).then(data => {
    if (data) {
      ctx.body = new SuccessModel({ list: data, userName: ctx.session.userName });
    } else {
      ctx.body = new ErrorModel(data)
    }
  })
})

router.get('/detail', async (ctx, next) => {
  const data = await getDetail(ctx.query.id)
  if (data) {
    ctx.body = new SuccessModel(data);
  } else {
    ctx.body = new ErrorModel(null, '博客不存在')
  }
})

router.post('/new', loginCheck, (ctx, next) => {
  const { title, content } = ctx.request.body
  const author = ctx.session.userName
  newBlog(title, content, author).then(insertId => {
    if (insertId) {
      ctx.body = new SuccessModel('新增成功');
    } else {
      ctx.body = new ErrorModel('新增失败');
    }
  })
})

router.post('/update', loginCheck, (ctx, next) => {
  const id = ctx.query.id
  const { title, content } = ctx.request.body
  updateBlog(title, content, id, ctx.session.userName, ctx.session.isAdmin).then(insertId => {
    if (insertId) {
      ctx.body = new SuccessModel('更新成功');
    } else {
      ctx.body = new ErrorModel('更新失败');
    }
  })
})

router.post('/delete', loginCheck, (ctx, next) => {
  deleteBlog(ctx.query.id, ctx.session.userName, ctx.session.isAdmin).then(affectedId => {
    if (affectedId) {
      ctx.body = new SuccessModel('删除成功');
    } else {
      ctx.body = new ErrorModel('删除失败');
    }
  })
})

module.exports = router;